import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth'
import { login, getUserInfo, getUserDetailById } from '@/api/user'
const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  // 设置token
  setToken(state, payload) {
    state.token = payload
    setToken(payload)// 缓存数据
  },
  // 删除缓存
  removeToken(state) {
    state.token = null
    removeToken()
  },
  // 设置用户资料
  setUserInfo(state, payload) {
    state.userInfo = payload
  },
  // 删除用户信息
  reomveUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  // 定义login action
  async login(context, payload) {
    const result = await login(payload)
    context.commit('setToken', result)
    // 设置时间戳
    setTimeStamp()
  },
  // 获取用户资料
  async getUserInfo(context) {
    const result = await getUserInfo()
    const detail = await getUserDetailById(result.userId)
    const baseInfo = { ...result, ...detail }// 将两个接口结果合并
    context.commit('setUserInfo', baseInfo)
    return baseInfo// 这里为什么要返回 为后面埋下伏笔
  },

  // 登出的action
  logout({ commit }) {
    // 删除token
    commit('removeToken')
    // 删除用户信息
    commit('reomveUserInfo')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
